import React, { Component } from 'react';
import {
	Form,
	Modal,
	Select,
	Button,
	Row,
	Col,
	List,
	Card,
	Typography
} from 'antd';
import { MinusCircleFilled } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import { groupJoin,resetGroupJoin } from 'src/services/DataManage';
import styles from '../index.module.scss';

interface Iprops {
	modalVisibleValue:boolean
	modalVisible:any
    aggData:any
	addNodeFunc:any
	addRelation:any
	joinComponentFunc:any
	setOutDataFunc:any
}


class Aggregation extends Component<Iprops,any> {
    state = {
    	value: { group: { data: [ 0 ] }, sum: { data: [ 0 ] }, avg: { data: [ 0 ] },
    		max: { data: [ 0 ] }, min: { data: [ 0 ] }, count: { data: [ 0 ] } },
    }

    formRef = React.createRef<FormInstance>()
    
    handleOk = async () => {
    	this.formRef.current.validateFields().then(
    		async value => {
    		    //去除为空的值
    			let fdata = Object.keys( value ).filter( item => value[item] );
    			let tmpData = {
    				'avg': fdata.filter( item => item.indexOf( 'avg' ) !== -1 ).map( item => value[item] ),
    				'count': fdata.filter( item => item.indexOf( 'count' ) !== -1 ).map( item => value[item] ),
    				'group': fdata.filter( item => item.indexOf( 'group' ) !== -1 ).map( item => value[item] ),
    				'max': fdata.filter( item => item.indexOf( 'max' ) !== -1 ).map( item => value[item] ),
    				'min': fdata.filter( item => item.indexOf( 'min' ) !== -1 ).map( item => value[item] ),
    				'sum': fdata.filter( item => item.indexOf( 'sum' ) !== -1 ).map( item => value[item] )
    			};
    			tmpData['count'] = tmpData['count'].length > 0 ? tmpData['count'][0] : '';
    			let rfdata = {
    				'fields': [],
    				'groups': tmpData,
    				
    				'position': 1
    			};
    			let info = null;
    			if( this.props.aggData.edit ) {
    				const { code,name } = this.props.aggData;
    				info = await resetGroupJoin( { data: { ...rfdata,componentCode: code,componentName: name } } );
    			}else {
    				info = await groupJoin( { data: { ...rfdata,'modelId': this.props.aggData.modelId } } );
    			}
    			if ( info.data.success ) {
    				//保存上一步的数据
    				let orData = null;
    				if( this.props.aggData.orignalData ) {
    					orData = this.props.aggData.orignalData;
    				}else {
    					orData = this.props.aggData;
    				}
    			    const data =  info.data.data;
    				let toData = { ...data,
    					form: value,
    					edit: this.props.aggData.edit,
    					fieldOrder: this.state.value,
    					orignalData: orData,
    					nodeType: 'aggregte' , 
    					style: { 'primaryColor': '#E9B28E' },
    					shape: 'SimplicityNode' };
    				this.props.joinComponentFunc( this.props.aggData,toData,{} );
    				this.handleCancel();
    			}
    		}
    	);
    }
    
    handleDel = ( item,index ) => {
    	const { value } = this.state;
    	value[item].data.splice( index,1 );
    	this.setState( value );
    }

    handleChange = ( it, item ) => {
    	const { value } = this.state;
    	let tmp = Math.max( ...value[it].data );
    	if( item === tmp && it.indexOf( 'count' ) === -1 ) {
    		value[it].data.push( tmp+1 );
    		this.setState( value ); 
    	}
    }
    
    handleCancel = () => {
    	this.props.modalVisible( 'aggVisible',false );
    	let data = this.props.aggData;
    	delete data.edit;
    	this.props.setOutDataFunc( data );
    	this.formRef.current.resetFields();
    	this.setState( {
    		value: { group: { data: [ 0 ] }, sum: { data: [ 0 ] }, avg: { data: [ 0 ] },
    			max: { data: [ 0 ] }, min: { data: [ 0 ] }, count: { data: [ 0 ] } },
    	} );
    }

    componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
    	if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.aggData.form &&this.props.aggData.edit ) {
    		if( this.props.modalVisibleValue !== prevProps.modalVisibleValue ) {
    			this.formRef.current.setFieldsValue( this.props.aggData.form );
    			this.setState( { value: this.props.aggData.fieldOrder } );
    		}
    	}

    }
    
    render() {
    	const names = [ '选择聚合字段（维度）','求汇总值字段（度量）','求平均值字段（度量）','求最大值字段（度量）','求最小值字段（度量）','计数字段' ];
    	const fieldMappings = this.props.aggData.edit&&this.props.aggData.orignalData
    		? this.props.aggData.orignalData.model.fieldMappings 
    		:this.props.aggData.model.fieldMappings;
    	return (
    		<Modal title={'字段聚合'}
    			visible={this.props.modalVisibleValue}
    			okText={'确定'}  mask={false} maskClosable={false}
    			width={1200}
    			onOk={this.handleOk}
    			onCancel={this.handleCancel }
    			cancelText={'取消'}>
    			<Form ref={this.formRef}>
    				{/*//头部*/}
    				<Row>
    					{
    						names.map( item => {
    							return (
    								<Col span={4} key={item}>
    								<Card bordered style={{ borderRadius: '0px',border: '1px solid #d9d9d9', 
    										background: '#F3F3F3' }} size="small">
    									<Typography  style={item.indexOf( '聚合' ) !== -1
    										?{ color: 'rgba( 103, 194, 58, 1 )',textAlign: 'center' }
    										:{ textAlign: 'center' }}>
    										{item}
    									</Typography>
    								</Card>
    								</Col>
    							);
    						} )
    					}
    				</Row>
    				{/*//选项区*/}
    				<Row justify={'space-around'}>
    					{
    						Object.keys( this.state.value ).map(
    							( it, idx ) => {
    								return (
    									<Col span={4} key={it}>
    										<List key={it} bordered style={{ borderRadius: '0px' }} >
    											{
    												this.state.value[it].data.map( ( item,index ) => {
    													return (
    														<List.Item key={item} style={{ justifyContent: 'start' }}>
    															<Form.Item name={`${it  }-${item}`} noStyle={true}>
    																<Select style={{ width: '90%' }} onChange={value => this.handleChange( it,item )}>
    																	{
    																		fieldMappings.map(
    																			( i,index ) => (
    																				// 'i.tempFieldName}'
    																					<Select.Option key={index} value={i.tempFieldName}>
    																						{i.finalFieldDesc}
    																					</Select.Option>
    																				) )
    																	}
    																</Select>
    															</Form.Item>
    															{
    																item !== Math.max( ...this.state.value[it].data )
    																	? ( <Button
    																		style={{ marginLeft: '6px',width: '8px' }}
    																		// shape='circle'
    																		type='text'
    																		// size={'small'}
    																		icon={<MinusCircleFilled className={ styles.greenBtn } />}
    																		onClick={() => {this.handleDel( it,index );}}/> )
    																	:null
    															}
    														</List.Item>
    													);
    												} )
    											}
    										</List>
    									</Col>
    								);
    							} )
    					}
    				</Row>
    			</Form>
    		</Modal>
    	);
    }
}

export default Aggregation;